package com.fhnew.app.ui.dialogactivity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.model.internet.been.B_Login;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.util.HLog;
import com.google.gson.Gson;
import com.fhnew.app.R;
import com.fhnew.app.global.Constants;
import com.fhnew.app.model.CustomObserver;
import com.fhnew.app.model.network.HttpJsonUtils;
import com.fhnew.app.model.network.entity.req.ResCode;
import com.fhnew.app.model.network.entity.req.Resmsg;
import com.fhnew.app.model.network.entity.req.Resregister;
import com.fhnew.app.util.Md5;
import com.fhnew.app.util.SYSOUtils;
import com.fhnew.app.util.SpUtils;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;


public class RegisterActivity extends Activity {

    ImageView close;
    TextView titletext;
    EditText rigistusername;
    EditText rigistrealname;
    EditText rigistphone;
    EditText rigistpass;
    EditText phonecode;
    EditText rigistidcode;
    EditText Invitation;
    EditText mInvitation;
    ImageView codeImg;
    TextView gorigist;
    LinearLayout rigistphonelayout;
    LinearLayout fullnamelayout;
    LinearLayout phoneloginlayout;
    LinearLayout Invitationlayout;
    LinearLayout mInvitationlayout;
    ScrollView codelayout;
    TextView codelogin;
    TextView ponelogin;
    View codeloginlin;
    View phoneloginlin;
    TextView phonelogin;
    TextView code_bt;
    TextView phoneforgetpassbt;
    EditText etuserphone;
    TextView phonename;


    private String peuser;
    private String username;
    private String password;
    private String password2;
    private String realname;
    private String phone;
    private String code;
    private String codes;

    private UserModel userModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_register);
        Constants.backgroundvoic = false;
        close = findViewById(R.id.close);
        titletext = findViewById(R.id.titletext);
        Invitationlayout = findViewById(R.id.Invitationlayout);
        mInvitationlayout = findViewById(R.id.mInvitationlayout);
        Invitation = findViewById(R.id.Invitation);
        mInvitation = findViewById(R.id.mInvitation);
        phoneloginlin = findViewById(R.id.phoneloginlin);
        phonename = findViewById(R.id.phonename);
        codeloginlin = findViewById(R.id.codeloginlin);
        rigistusername = findViewById(R.id.rigistusername);
        rigistrealname = findViewById(R.id.rigistrealname);
        fullnamelayout = findViewById(R.id.fullnamelayout);
        rigistphone = findViewById(R.id.rigistphone);
        rigistpass = findViewById(R.id.rigistpass);
        rigistidcode = findViewById(R.id.rigistidcode);
        codeImg = findViewById(R.id.code_img);
        gorigist = findViewById(R.id.gorigist);
        etuserphone = findViewById(R.id.etuserphone);
        codelayout = findViewById(R.id.codelayout);
        rigistphonelayout = findViewById(R.id.rigistphonelayout);
        codelogin = findViewById(R.id.codelogin);
        ponelogin = findViewById(R.id.ponelogin);
        phonelogin = findViewById(R.id.phonelogin);
        phoneloginlayout = findViewById(R.id.phoneloginlayout);
        phonecode = findViewById(R.id.phonecode);
        code_bt = findViewById(R.id.code_bt);
        phoneforgetpassbt = findViewById(R.id.phoneforgetpassbt);
        if (Constants.agentModel == 2) {
            //显示推荐人
            Invitationlayout.setVisibility(View.VISIBLE);
            mInvitationlayout.setVisibility(View.VISIBLE);
        } else {
            Invitationlayout.setVisibility(View.GONE);
            mInvitationlayout.setVisibility(View.GONE);

        }
        phoneforgetpassbt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                startActivity(new Intent(RegisterActivity.this, ForgetActivity.class));
            }
        });


        phonelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etuserphone.getText().toString().trim()) && !TextUtils.isEmpty(phonecode.getText().toString().trim())) {
                    phonelogin(etuserphone.getText().toString().trim(), phonecode.getText().toString().trim(), mInvitation.getText().toString().trim());
                } else {
                    Toast.makeText(RegisterActivity.this, "请输入正确信息", Toast.LENGTH_SHORT).show();
                }
            }
        });


        code_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(etuserphone.getText().toString().trim())) {
                    sendmsg(etuserphone.getText().toString().trim());

                } else {
                    Toast.makeText(RegisterActivity.this, "请输入手机号", Toast.LENGTH_SHORT).show();
                }
            }
        });
        codelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                codelogin.setTextColor(getResources().getColor(R.color.moccasin));
                ponelogin.setTextColor(getResources().getColor(R.color.settingbg));
                codeloginlin.setBackgroundResource(R.color.moccasin);
                phoneloginlin.setBackgroundResource(R.color.settingbg);
                codeloginlin.setVisibility(View.VISIBLE);
                phoneloginlin.setVisibility(View.INVISIBLE);
                codelayout.setVisibility(View.VISIBLE);
                phoneloginlayout.setVisibility(View.GONE);

            }
        });
        ponelogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ponelogin.setTextColor(getResources().getColor(R.color.moccasin));
                codelogin.setTextColor(getResources().getColor(R.color.settingbg));
                phoneloginlin.setBackgroundResource(R.color.moccasin);
                codeloginlin.setBackgroundResource(R.color.settingbg);
                phoneloginlin.setVisibility(View.VISIBLE);
                codeloginlin.setVisibility(View.INVISIBLE);
                codelayout.setVisibility(View.GONE);
                phoneloginlayout.setVisibility(View.VISIBLE);

            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        codeImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getcode();
            }
        });
        gorigist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = rigistusername.getText().toString().trim();//账号
                password = rigistpass.getText().toString().trim();//密码
                realname = rigistrealname.getText().toString().trim();//真实姓名
                phone = rigistphone.getText().toString().trim();//手机号
                code = rigistidcode.getText().toString().trim();//用户输入的验证码
                peuser = Invitation.getText().toString().trim();//推荐码
                if (TextUtils.isEmpty(username)) {
                    Toast.makeText(RegisterActivity.this, "请输入账号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(RegisterActivity.this, "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (!password.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z_]{6,}$")) {
                    Toast.makeText(RegisterActivity.this, "您的密码不符合规定", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(code)) {
                    Toast.makeText(RegisterActivity.this, "请输入验证码", Toast.LENGTH_LONG).show();
                    return;
                }

                String password1 = Md5.toMd5(password);
                register(username, password1, realname, phone, peuser, codes, code);
            }
        });


        getcode();

        initConstants();

    }

    private void sendmsg(String trim) {
        HttpJsonUtils.getHttpApiInstance()
                .sendmsg(Constants.getuseAdress() + "api/m/smsCode/" + trim, "1", "")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resmsg>() {
                    @Override
                    protected void onCustomNext(Resmsg resLogin) {
                        if (resLogin.status) {
                            //成功
                            timer.start();
                            Toast.makeText(RegisterActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(RegisterActivity.this, resLogin.msg, Toast.LENGTH_SHORT).show();
                            timer.cancel();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });
    }

    private void phonelogin(String s, String trim, String trim1) {
        HttpJsonUtils.getHttpApiInstance()
                .mobileLogin(Constants.getuseAdress() + "api/m/mobileLogin", s, trim, trim1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<B_Login>() {
                    @Override
                    protected void onCustomNext(B_Login resLogin) {
                        if (resLogin.getCode() == 0 && resLogin.getData() != null) {
//                            UserModel.user = resLogin.getData();
//                            UserModel.Token = resLogin.getData().token;
//                            SpUtils.putString(RegisterActivity.this, "User", new Gson().toJson(resLogin.getData()));
                            userModel.login(resLogin.getData());

                            Toast.makeText(RegisterActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(RegisterActivity.this, "" + resLogin.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }
                });

    }

    private void register(String username, String password1, String realname, String phone, String peuser, String codes, String code) {
        HttpJsonUtils.getHttpApiInstance()
                .register(Constants.getuseAdress() + "api/m/reg", username, password1, realname, phone, "", codes, code, peuser,"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<Resregister>() {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        getcode();
                    }

                    @Override
                    protected void onCustomNext(Resregister resregister) {
                        if (resregister.code != 0) {
                            Toast.makeText(RegisterActivity.this, resregister.msg, Toast.LENGTH_SHORT).show();
                            getcode();
                        } else {
                            //轮询用户信息
                            String password1 = Md5.toMd5(password);
                            SYSOUtils.sOut_("++++++++++++++++++++++" + password1);
                            finduser(resregister.data.token);
                        }
                    }
                });
    }

    private void finduser(String s) {

        HttpJsonUtils.getHttpApiInstance()
                .init(Constants.getuseAdress() + "api/init", s)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<B_Login.DataBean>() {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {

                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {
                        Toast.makeText(RegisterActivity.this, "查询失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    protected void onCustomNext(B_Login.DataBean resLogin) {
                        if (resLogin.getCode() == 0) {
                            UserModel.user = resLogin;
                            UserModel.Token = resLogin.token;

                            userModel.login(resLogin);

                            SpUtils.putString(RegisterActivity.this, "User", new Gson().toJson(resLogin));
                            Toast.makeText(RegisterActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                            finish();
                        } else {
                            Toast.makeText(RegisterActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void getcode() {
        HttpJsonUtils.getHttpApiInstance()
                .getcode(Constants.getuseAdress() + "api/m/captcha")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CustomObserver<ResCode>() {
                    @Override
                    protected void onSubscribeCustom(Disposable disposable) {
                    }

                    @Override
                    protected void onErrorCustom(Throwable e) {

                    }

                    @Override
                    protected void onCustomNext(ResCode resCode) {
                        if (null != resCode.data) {
                            switch (resCode.data.register_type) {
                                case 0:
                                    rigistphonelayout.setVisibility(View.GONE);
                                    break;
                                case 1:
                                    rigistphonelayout.setVisibility(View.VISIBLE);
                                    rigistphone.setHint("11位手机号");
                                    phonename.setText("手机号");
                                    break;
                                case 2:
                                    rigistphonelayout.setVisibility(View.VISIBLE);
                                    rigistphone.setHint("请输入qq号");
                                    phonename.setText("qq号");
                                    break;
                                case 3:
                                    rigistphonelayout.setVisibility(View.VISIBLE);
                                    rigistphone.setHint("请输入微信号");
                                    phonename.setText("微信号");
                                    break;
                                default:
                                    Toast.makeText(RegisterActivity.this, "验证码接口返回有误", Toast.LENGTH_SHORT).show();
                                    break;
                            }
                            if (resCode.data.is_reg_fullname == 2) {
                                fullnamelayout.setVisibility(View.GONE);
                            }
                            codes = "";
                            codes = resCode.data.captcha_code;
                            Bitmap bitmap = null;
                            byte[] bitmapArray;
                            bitmapArray = Base64.decode(resCode.data.code, Base64.NO_WRAP);
                            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length);
                            codeImg.setImageBitmap(bitmap);//显示图片
                        }
                    }
                });
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            code_bt.setText((millisUntilFinished / 1000) + "S后重发");
            code_bt.setEnabled(false);
        }

        @Override
        public void onFinish() {
            code_bt.setEnabled(true);
            code_bt.setText("获取验证码");
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }


    private void initConstants(){
        userModel = UserModel.getInstance(this);

    }

}
